package br.com.async.agilequiz.controller.user;

import java.util.List;

import android.database.SQLException;
import br.com.async.agilequiz.database.DatabaseHelper;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

public class UserDao {

	Dao<User, Integer> userDao;
	
	public UserDao(DatabaseHelper db){
		try {
			userDao = db.getDao(User.class);
		} catch (SQLException e) {
			// TODO: Exception Handling
			e.printStackTrace();
		} catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void create(User user){
		try {
			userDao.create(user);
			System.out.println("User created!");
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void update(User user){
		try {
			userDao.update(user);
			System.out.println("User updated!");
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void delete(User user){
		try {
			userDao.delete(user);
			System.out.println("User deleted!");
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public User getUserById(Integer id){
		try{
			
			QueryBuilder<User, Integer> qb = userDao.queryBuilder();
			qb.where().eq("id",id);
			PreparedQuery<User> pq = qb.prepare();
			return userDao.queryForFirst(pq);
			
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public User getUserByName(String username){		
		try {
			QueryBuilder<User, Integer> qb = userDao.queryBuilder();
			qb.where().eq("username",username);
			
			PreparedQuery<User> pq = qb.prepare();
			
			return userDao.queryForFirst(pq);
		
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public boolean getUser(String username, String password) {
		try {
			QueryBuilder<User, Integer> qb = userDao.queryBuilder();
			qb.where().eq("username",username);
			qb.where().eq("password",password);
			
			PreparedQuery<User> pq = qb.prepare();
			
			if(userDao.queryForFirst(pq) != null)
				return true;
		
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	
	
	public List<User> getAll(){		
		try {
			return userDao.queryForAll();
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	
	
}
